"""
@function
Get access token for wenxin

@cron
0 0 1,21 * *

@command
python3 update_access_token.py

@detail
Get access token for wenxin via HTTPS and store it in file './access_token'.

Reference: 
[1] https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Ilkkrb0i5
[2] https://cloud.baidu.com/doc/WENXINWORKSHOP/s/Dlkm79mnx
"""
import os
import json
import pprint
import logging
import requests
from datetime import datetime
from logging.handlers import RotatingFileHandler

log_file = os.path.expanduser('~/.my-tools/log/study/update_access_token.log')
os.makedirs(os.path.dirname(log_file), exist_ok=True)

log_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler = RotatingFileHandler(log_file, maxBytes=100*1024*1024, backupCount=2)  # 100 MB per file, 2 backup
handler.setFormatter(log_formatter)
logger = logging.getLogger('report')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)

def read_json(file_path):
    with open(file_path, "r", encoding="utf-8") as file:
        config = json.load(file)
    return config

def save_access_token(token, filename='./access_token'):
    with open(filename, 'w') as file:
        file.write(token)

"""
Useful responses:
    access_token,
    expires_in,
    error (when failed),
    error_description (when failed)
"""
def get_access_token(api_key, secret_key):
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    params = {
        'grant_type': 'client_credentials',
        'client_id': api_key,
        'client_secret': secret_key
    }
    
    response = requests.post(url, params=params)
    return response.json()

if __name__ == '__main__':
    config = read_json('./config.json')
    api_key = config['API Key']
    secret_key = config['Secret Key']
    token_info = get_access_token(api_key, secret_key)
    pprint.pprint(token_info)

    if 'error' in token_info and 'error_description' in token_info:
        logger.error(f"Error occured: {token_info['error_description']}.")
    
    if 'access_token' in token_info:
        save_access_token(token_info['access_token'])
        logger.debug(f"Saving access token into file successfully: {token_info}")